package com.nengchuan.eic.nceconomy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.nengchuan.eic.nceconomy.config.BaseConfig;
import com.nengchuan.eic.nceconomy.constant.CommonConstant;
import com.nengchuan.eic.nceconomy.constant.SwFileComputeStatusEnum;
import com.nengchuan.eic.nceconomy.entity.dto.SwFilePageDTO;
import com.nengchuan.eic.nceconomy.entity.dto.SwFileSaveDTO;
import com.nengchuan.eic.nceconomy.entity.po.SwDirectory;
import com.nengchuan.eic.nceconomy.entity.po.SwFile;
import com.nengchuan.eic.nceconomy.dao.SwFileMapper;
import com.nengchuan.eic.nceconomy.entity.vo.OssFileReseponseVO;
import com.nengchuan.eic.nceconomy.entity.vo.SwDirectoryVO;
import com.nengchuan.eic.nceconomy.entity.vo.SwFileVO;
import com.nengchuan.eic.nceconomy.fegin.ReportFeignService;
import com.nengchuan.eic.nceconomy.service.SwFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nengchuan.model.model.WrappedResult;
import com.nengchuan.util.MapperUtils;
import com.nengchuan.util.NullCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author panwen
 * @since 2020-05-25
 */
@Service
@Slf4j
public class SwFileServiceImpl extends ServiceImpl<SwFileMapper, SwFile> implements SwFileService {
    private final static Logger logger = LoggerFactory.getLogger(SwFileServiceImpl.class);
    @Autowired
    private OssService ossService;

    @Autowired
    private BaseConfig baseConfig;

    @Autowired
    private ReportFeignService reportFeignService;

    @Override
    public List<SwFileVO> page(SwFilePageDTO dto){
        LambdaQueryWrapper<SwFile> queryWrapper=new QueryWrapper<SwFile>().lambda()
                .eq(SwFile::getDirectoryId,dto.getDirectoryId())
                .eq(SwFile::getFileType,dto.getFileType())
                .orderByDesc(SwFile::getSort);

        if(NullCheckUtils.isNotNull(dto.getFileName())){
            queryWrapper.like(SwFile::getFileName,dto.getFileName());
        }

        if(NullCheckUtils.isNotNull(dto.getComputeStatus())){
            queryWrapper.eq(SwFile::getComputeStatus,dto.getComputeStatus());
        }

        if(NullCheckUtils.isNotNull(dto.getProjectType())){
            queryWrapper.eq(SwFile::getProjectType,dto.getProjectType());
        }
        List<SwFile> list = this.list(queryWrapper);
//        Page<SwFile> page=new Page<>(dto.getPageNum(),dto.getPageSize());
//        IPage<SwFile> swFileIPage=this.page(page,queryWrapper);
//        List<SwFile> records=page.getRecords();

//        PageInfo<SwFileVO> pageInfo = new PageInfo<>();

//        if(NullCheckUtils.isNotNull(records)) {
//            pageInfo.setPageNum((int) swFileIPage.getCurrent());
//            pageInfo.setPageSize((int) swFileIPage.getSize());
//            pageInfo.setTotal(swFileIPage.getTotal());
//            pageInfo.setList(MapperUtils.mappingList(records, SwFileVO.class));
//        }
        return MapperUtils.mappingList(list, SwFileVO.class);
    }

    /**
     * 同步文件计算状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncFileComputeStatus(){
        LambdaQueryWrapper<SwFile> queryWrapper=new QueryWrapper<SwFile>().lambda().eq(SwFile::getComputeStatus,SwFileComputeStatusEnum.COMPUTEING.status);
        List<SwFile> swFiles=this.list(queryWrapper);
        log.info("#syncFileComputeStatus# 正在同步三维算量云文件汇总计算状态; [需要同步数量:{}]",swFiles.size());

        if(NullCheckUtils.isNull(swFiles)){
            return;
        }

        swFiles.forEach(e->{
            //获取汇总文件计算状态
            WrappedResult wrappedResult = reportFeignService.cloudFileStatus(e.getId());
            if(wrappedResult!=null&&wrappedResult.getCode()==0&&wrappedResult.getData()!=null){
                switch ((String)wrappedResult.getData()){
                    case "13":
                        e.setComputeStatus(SwFileComputeStatusEnum.COMPUTEING.status);
                        e.setQueryNum(e.getQueryNum()+1);
                        break;
                    case "14":
                        e.setComputeStatus(SwFileComputeStatusEnum.COMPUTE_SUCCESS.status);
                        e.setQueryNum(e.getQueryNum()+1);
                        break;
                    case "15":
                        e.setComputeStatus(SwFileComputeStatusEnum.COMPUTE_FAIL.status);
                        e.setQueryNum(e.getQueryNum()+1);
                        break;
                    default:
                        e.setComputeStatus(SwFileComputeStatusEnum.COMPUTE_FAIL.status);
                        e.setQueryNum(e.getQueryNum()+1);
                        break;
                }
            }
        });

        this.updateBatchById(swFiles);
        log.info("#syncFileComputeStatus# 云文件同步汇总计算状态完毕; [同步数量:{}]",swFiles.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertOrUpdate(SwFileSaveDTO dto) throws Exception {
        SwFile swFile= MapperUtils.mapping(dto,SwFile.class);
        WrappedResult<OssFileReseponseVO> filesFromOssById = ossService.getFilesFromOssById(dto.getOssId());
        if(dto.getExcelId()!=null){
            WrappedResult<OssFileReseponseVO> filesFromOssById1 = ossService.getFilesFromOssById(dto.getExcelId());
            swFile.setExcelUrl(filesFromOssById1!=null?filesFromOssById1.getData().getUrl():null);
        }

//        Long ossId=1L;
//        if(!"dev".equals(baseConfig.getSpringProfileActive())){
//            ossId=ossService.uploadByOss(file);
//        }
        logger.info("获取文件信息--ossid:{},info:{}",dto.getOssId(),new ObjectMapper().writeValueAsString(filesFromOssById));
        swFile.setOssUrl(CommonConstant.TEMFILE.get(dto.getProjectType()));
        swFile.setComputeStatus(SwFileComputeStatusEnum.NOT_COMPUTE.status);
        swFile.setFileName(filesFromOssById!=null?filesFromOssById.getData().getFileName():null);

        return this.saveOrUpdate(swFile);
    }
}
